<template>
  <div class="space-y-6">
    <div class="flex justify-between items-center">
      <h2 class="text-xl font-semibold text-gray-800">模板管理</h2>
      <div class="flex gap-2">
        <button
          @click="selectTemplatesFolder"
          :disabled="importing"
          class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          {{ importing ? '导入中...' : '选择模板文件夹' }}
        </button>
        <button
          v-if="currentFolder"
          @click="reimportFromCurrentFolder"
          :disabled="importing"
          class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          重新导入
        </button>
      </div>
    </div>

    <!-- 当前文件夹显示 -->
    <div v-if="currentFolder" class="bg-blue-50 border border-blue-200 rounded-lg p-3 flex items-center justify-between">
      <div class="flex items-center gap-2">
        <span class="text-sm text-blue-700">当前模板文件夹：</span>
        <span class="text-sm font-medium text-blue-900">{{ currentFolder }}</span>
      </div>
      <button
        @click="clearFolder"
        class="text-xs text-blue-600 hover:text-blue-800"
      >
        清除
      </button>
    </div>

    <!-- 模板列表 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      <div
        v-for="template in templates"
        :key="template.id"
        class="bg-white rounded-lg shadow p-4 hover:shadow-md transition-shadow"
      >
        <div class="flex items-start justify-between gap-2 mb-2">
          <h3 class="font-semibold text-gray-800 flex-1 min-w-0 pr-2 line-clamp-2">{{ template.name }}</h3>
          <div class="flex items-center gap-1.5 flex-shrink-0">
            <span
              v-if="template.type === 'docx'"
              class="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs whitespace-nowrap"
            >
              DOCX
            </span>
            <span
              v-else
              class="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs whitespace-nowrap"
            >
              文本
            </span>
            <span
              v-if="template.category"
              class="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs whitespace-nowrap max-w-[80px] truncate"
              :title="template.category"
            >
              {{ template.category }}
            </span>
          </div>
        </div>
        
        <!-- 描述信息 -->
        <p v-if="template.description" class="text-sm text-gray-600 mb-2 line-clamp-2">
          {{ template.description }}
        </p>
        <p v-else-if="template.type === 'text'" class="text-sm text-gray-500 mb-2 line-clamp-2">{{ template.content }}</p>
        <p v-else class="text-sm text-gray-500 mb-2">DOCX 文件模板</p>
        
        <!-- 使用场景 -->
        <p v-if="template.scene" class="text-xs text-gray-400 mb-2">
          <span class="font-medium">使用场景：</span>{{ template.scene }}
        </p>
        
        <div class="flex items-center justify-between text-xs text-gray-400 mb-3">
          <span>{{ template.variables?.length || 0 }} 个变量</span>
          <span v-if="template.updatedAt">{{ template.updatedAt }}</span>
        </div>
        
        <div class="mt-3 flex gap-2">
          <button
            @click="editTemplate(template)"
            class="flex-1 px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 text-sm"
          >
            编辑
          </button>
          <button
            @click="deleteTemplate(template.id)"
            class="flex-1 px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 text-sm"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑模态框 -->
    <div
      v-if="showCreateModal || editingTemplate"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
      @click.self="closeModal"
    >
      <div class="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[80vh] overflow-auto">
        <h3 class="text-lg font-semibold mb-4">
          {{ editingTemplate ? '编辑模板' : (templateType === 'docx' ? '上传 DOCX 模板' : '新建文本模板') }}
        </h3>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">模板名称</label>
            <input
              v-model="formData.name"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入模板名称"
            />
          </div>
          
          <!-- DOCX 文件上传 -->
          <div v-if="templateType === 'docx' && !editingTemplate">
            <label class="block text-sm font-medium text-gray-700 mb-1">上传 DOCX 文件</label>
            <div
              @drop.prevent="handleDocxDrop"
              @dragover.prevent
              @dragenter.prevent
              class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-500 transition-colors cursor-pointer"
            >
              <input
                ref="docxInput"
                type="file"
                accept=".docx"
                @change="handleDocxSelect"
                class="hidden"
              />
              
              <div v-if="!selectedDocxFile" @click="$refs.docxInput.click()">
                <p class="text-gray-500 mb-2">点击或拖拽 DOCX 文件到这里</p>
                <p class="text-sm text-gray-400">支持 .docx 格式，使用 {{变量名}} 作为占位符</p>
              </div>
              
              <div v-else class="space-y-2">
                <p class="text-sm text-gray-600">已选择：{{ selectedDocxFile.name }}</p>
                <button
                  @click.stop="clearDocxFile"
                  class="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 text-sm"
                >
                  重新选择
                </button>
              </div>
            </div>
            <p class="mt-1 text-xs text-gray-500">
              提示：在 DOCX 文件中使用 {{变量名}} 格式定义变量，例如：{{姓名}}、{{身份证号}}
            </p>
          </div>
          
          <!-- 文本模板内容 -->
          <div v-if="templateType === 'text'">
            <label class="block text-sm font-medium text-gray-700 mb-1">模板内容</label>
            <textarea
              v-model="formData.content"
              rows="10"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
              placeholder="请输入模板内容，使用 {{变量名}} 作为占位符，例如：姓名：{{姓名}}"
            ></textarea>
            <p class="mt-1 text-xs text-gray-500">
              提示：使用 {{变量名}} 格式定义变量，例如：{{姓名}}、{{身份证号}}
            </p>
          </div>
          
          <div v-if="extractedVariables.length > 0">
            <label class="block text-sm font-medium text-gray-700 mb-1">检测到的变量</label>
            <div class="flex flex-wrap gap-2">
              <span
                v-for="varName in extractedVariables"
                :key="varName"
                class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-sm"
              >
                {{ varName }}
              </span>
            </div>
          </div>
        </div>
        
        <div class="mt-6 flex justify-end gap-3">
          <button
            @click="closeModal"
            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            取消
          </button>
          <button
            @click="saveTemplate"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { templateAPI, fileAPI } from '../api/app.js'

const templates = ref([])
const currentFolder = ref('')
const importing = ref(false)
const showCreateModal = ref(false)
const editingTemplate = ref(null)
const templateType = ref('text') // 'text' 或 'docx'
const selectedDocxFile = ref(null)
const docxInput = ref(null)
const formData = ref({
  name: '',
  content: '',
})

const extractedVariables = computed(() => {
  const content = formData.value.content
  const variables = []
  const regex = /\{\{(\w+)\}\}/g
  let match
  const seen = new Set()
  
  while ((match = regex.exec(content)) !== null) {
    const varName = match[1]
    if (!seen.has(varName)) {
      variables.push(varName)
      seen.add(varName)
    }
  }
  
  return variables
})

const loadTemplates = async () => {
  try {
    templates.value = await templateAPI.list()
  } catch (error) {
    console.error('加载模板失败:', error)
    alert('加载模板失败: ' + error.message)
  }
}

const editTemplate = async (template) => {
  try {
    // 获取模板 ID 和完整模板信息
    const templateId = typeof template === 'string' ? template : template.id
    const fullTemplate = typeof template === 'string' 
      ? JSON.parse(await templateAPI.get(template))
      : template
    
    console.log('编辑模板 - 完整数据:', fullTemplate)
    console.log('模板类型:', fullTemplate.type, '文件路径:', fullTemplate.filePath)
    
    // 检查是否是 DOCX 模板（不区分大小写）
    const isDocx = fullTemplate.type && fullTemplate.type.toLowerCase() === 'docx'
    
    // 如果是 DOCX 模板且有文件路径，使用系统默认程序打开文件
    if (isDocx && fullTemplate.filePath) {
      console.log('尝试打开 DOCX 文件:', fullTemplate.filePath)
      try {
        await fileAPI.openFile(fullTemplate.filePath)
        console.log('文件打开成功')
        return
      } catch (error) {
        console.error('打开文件失败:', error)
        alert('打开文件失败: ' + error.message)
        return
      }
    }
    
    // 如果是 DOCX 但没有文件路径，提示用户
    if (isDocx && !fullTemplate.filePath) {
      console.warn('DOCX 模板缺少文件路径')
      alert('无法获取 DOCX 文件路径，使用弹窗编辑')
    }
    
    // 文本模板或没有 filePath 的 DOCX 模板使用弹窗编辑
    console.log('使用弹窗编辑模板')
    editingTemplate.value = fullTemplate
    formData.value = {
      name: fullTemplate.name,
      content: fullTemplate.content || '',
    }
    showCreateModal.value = true
  } catch (error) {
    console.error('加载模板失败:', error)
    alert('加载模板失败: ' + error.message)
  }
}

const deleteTemplate = async (id) => {
  if (!confirm('确定要删除这个模板吗？')) return
  
  try {
    await templateAPI.delete(id)
    await loadTemplates()
  } catch (error) {
    console.error('删除模板失败:', error)
    alert('删除模板失败: ' + error.message)
  }
}

const saveTemplate = async () => {
  if (!formData.value.name.trim()) {
    alert('请输入模板名称')
    return
  }
  
  try {
    if (editingTemplate.value) {
      // 编辑模式暂时只支持文本模板
      if (!formData.value.content.trim()) {
        alert('请输入模板内容')
        return
      }
      await templateAPI.update(
        editingTemplate.value.id,
        formData.value.name,
        formData.value.content
      )
    } else {
      if (templateType.value === 'docx') {
        // 上传 DOCX 文件
        if (!selectedDocxFile.value) {
          alert('请选择 DOCX 文件')
          return
        }
        
        // 读取文件并转换为 base64
        const reader = new FileReader()
        reader.onload = async (e) => {
          try {
            const base64Data = e.target.result
            await templateAPI.createDocx(formData.value.name, base64Data)
            closeModal()
            await loadTemplates()
          } catch (error) {
            console.error('保存模板失败:', error)
            alert('保存模板失败: ' + error.message)
          }
        }
        reader.readAsDataURL(selectedDocxFile.value)
        return
      } else {
        // 创建文本模板
        if (!formData.value.content.trim()) {
          alert('请输入模板内容')
          return
        }
        await templateAPI.create(formData.value.name, formData.value.content)
      }
    }
    
    closeModal()
    await loadTemplates()
  } catch (error) {
    console.error('保存模板失败:', error)
    alert('保存模板失败: ' + error.message)
  }
}

const handleDocxSelect = (event) => {
  const file = event.target.files[0]
  if (file && file.name.endsWith('.docx')) {
    selectedDocxFile.value = file
  } else {
    alert('请选择 .docx 格式的文件')
  }
}

const handleDocxDrop = (event) => {
  const file = event.dataTransfer.files[0]
  if (file && file.name.endsWith('.docx')) {
    selectedDocxFile.value = file
  } else {
    alert('请选择 .docx 格式的文件')
  }
}

const clearDocxFile = () => {
  selectedDocxFile.value = null
  if (docxInput.value) {
    docxInput.value.value = ''
  }
}

const closeModal = () => {
  showCreateModal.value = false
  editingTemplate.value = null
  templateType.value = 'text'
  selectedDocxFile.value = null
  formData.value = {
    name: '',
    content: '',
  }
}

const selectTemplatesFolder = async () => {
  try {
    const folderPath = await templateAPI.selectFolder()
    if (!folderPath) {
      return // 用户取消
    }
    
    await importFromFolder(folderPath)
  } catch (error) {
    console.error('选择文件夹失败:', error)
    alert('选择文件夹失败: ' + error.message)
  }
}

const importFromFolder = async (folderPath) => {
  importing.value = true
  try {
    const importedTemplates = await templateAPI.importFromFolder(folderPath)
    currentFolder.value = folderPath
    await loadTemplates()
    alert(`成功导入 ${importedTemplates.length} 个模板`)
  } catch (error) {
    console.error('导入模板失败:', error)
    alert('导入模板失败: ' + error.message)
  } finally {
    importing.value = false
  }
}

const reimportFromCurrentFolder = async () => {
  if (currentFolder.value) {
    await importFromFolder(currentFolder.value)
  }
}

const clearFolder = () => {
  currentFolder.value = ''
}

const loadDefaultFolder = async () => {
  try {
    const defaultFolder = await templateAPI.getDefaultFolder()
    if (defaultFolder) {
      // 检查默认文件夹是否存在且有文件
      currentFolder.value = defaultFolder
      // 自动导入默认文件夹
      await importFromFolder(defaultFolder)
    }
  } catch (error) {
    console.error('加载默认文件夹失败:', error)
  }
}

// 模板已在应用启动时加载，这里只显示
onMounted(() => {
  // 直接加载模板列表（从缓存读取）
  loadTemplates()
  // 加载默认文件夹信息（不自动导入）
  loadDefaultFolderInfo()
})

const loadDefaultFolderInfo = async () => {
  try {
    const defaultFolder = await templateAPI.getDefaultFolder()
    if (defaultFolder) {
      currentFolder.value = defaultFolder
    }
  } catch (error) {
    console.error('加载默认文件夹信息失败:', error)
  }
}
</script>

